//
//  GJAddressSearchViewController.m
//  xmgjAppFront
//
//  Created by Zeki on 2020/7/27.
//  Copyright © 2020 guojutech. All rights reserved.
//

#import "GJAddressSearchViewController.h"


#import "GJMapSearchBarView.h"
#import "GJMapSelectedPointBottmView.h"
#import "GJSearchTableView.h"


#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

@interface GJAddressSearchViewController ()<MAMapViewDelegate>


//searchbar
@property (nonatomic, strong)GJMapSearchBarView *searchbar;
//当前界面的mapView
@property (nonatomic, strong) MAMapView *mapView;
//返回按钮
@property (nonatomic, strong) UIButton *backButton;
//定位按钮
@property (nonatomic, strong) UIButton *locationButton;
//定位工具
@property (nonatomic, strong) GJLocationUtil *util;
//当前选中经纬度
@property (nonatomic, strong)  CLLocation *currentLocation;
//地图底部列表
@property (nonatomic, strong) GJMapSelectedPointBottmView *bottomView;
//搜索视图
@property (nonatomic, strong) GJSearchTableView *searchTableView;
//是否在搜索页面
@property (nonatomic, assign) BOOL isSearching;
//关键字搜索之后
//@property (nonatomic, strong) __block BMKSuggestionInfo *searchSuggestionInfo;
//navigation
@property (nonatomic, strong)UIView *navigatinoView;

//选中的地址信息
//@property (nonatomic, strong)BMKPoiInfo *uploadInfo;
@end

@implementation GJAddressSearchViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  if (@available(iOS 11.0, *)) {
    self.bottomView.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  } else {
    self.automaticallyAdjustsScrollViewInsets = NO;
  }
  self.view.backgroundColor = [UIColor whiteColor];
  
  //处理初始数据
  self.addressDic = self.queryParameters;
  if ([self.addressDic[@"lat"] gj_hasValue] && [self.addressDic[@"lon"] gj_hasValue]) {
    self.centerLocation = CLLocationCoordinate2DMake([self.addressDic[@"lat"] gj_hasValue] ? [self.addressDic[@"lat"] floatValue] : 0, [self.addressDic[@"lon"] gj_hasValue] ? [self.addressDic[@"lon"] floatValue] : 0);
  }
  
  
  [self initlizationSubViews];
  
  
  self.searchbar.dataDictionary = self.addressDic;
  self.bottomView.buttonTitle = [self.addressDic[@"type"] gj_hasValue] ? self.addressDic[@"type"]:@"设为装货点";
  if (!CLLocationCoordinate2DIsValid(self.centerLocation)) {
    [self updateLocation];
  }else{
    [self queryLocationGeoWith:self.centerLocation];
  }
  
  
  [self searchActions];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  [self.view endEditing:YES];
}
- (void)initlizationSubViews{
  
  
  [self.view addSubview:self.mapView];
  [self.view addSubview:self.navigatinoView];
  [self.navigatinoView addSubview:self.backButton];
  [self.navigatinoView addSubview:self.searchbar];
  
  [self.navigatinoView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.left.right.equalTo(self.view);
    make.height.mas_equalTo(kSafeNavigationBarHeight);
  }];
  
  [self.searchbar mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(42);
    make.right.mas_equalTo(-16);
    make.height.mas_equalTo(34);
    make.top.mas_equalTo(kSafeStatusBarHeight + 7);
  }];
  [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.searchbar);
    make.left.mas_equalTo(0);
    make.right.equalTo(self.searchbar.mas_left);
    make.height.mas_equalTo(40);
  }];
  
  [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
    //    make.top.equalTo(self.searchbar.mas_bottom).offset(7);
    make.top.mas_equalTo(-278*0.5 - 30);
    make.left.right.bottom.equalTo(self.view);
  }];
  
  [self.mapView addSubview:self.locationButton];
  [self.mapView addSubview:self.bottomView];
  
  [self.locationButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(12);
    make.width.height.mas_equalTo(38);
    make.bottom.equalTo(self.bottomView.mas_top).offset(-16);
  }];
  [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.mas_equalTo(-40-kSafeBottomAreaHeight);
    make.left.mas_equalTo(12);
    make.right.mas_equalTo(-12);
    make.height.mas_equalTo(278);
  }];
  
  [self.view addSubview:self.searchTableView];
  [self.searchTableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.width.equalTo(self.mapView);
    make.top.mas_equalTo(kSafeNavigationBarHeight);
    make.left.equalTo(self.view).offset(kScreenWidth);
  }];
}

- (void)searchActions{
  @weakify(self);
  self.searchbar.textFieldBlock = ^(NSString * _Nonnull text, BOOL isbeginEditing, BOOL isEndEditing) {
    @strongify(self);
    if (isbeginEditing) {
      self.isSearching = YES;
      dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.5 animations:^{
          [self.searchTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
          }];
        }];
      });
      
      
      return;
    }
  };
  
  self.searchbar.keyWordsPoiSearchBlock = ^(NSArray * _Nonnull result) {
    @strongify(self);
    self.searchTableView.dataArray = result;
  };
  self.searchTableView.selectedCellBlock = ^(NSIndexPath * _Nonnull indexPath, NSArray * _Nonnull dataArray) {
    @strongify(self);
    NSDictionary *poiInfo = dataArray[indexPath.row];
    self.searchbar.address = poiInfo[@"address"];
    self.searchbar.dataDictionary  = @{@"city":[poiInfo[@"city"] gj_hasValue]?poiInfo[@"city"]:@"",@"area":[poiInfo[@"district"] gj_hasValue]?poiInfo[@"district"]:@""};
    dispatch_async(dispatch_get_main_queue(), ^{
      [UIView animateWithDuration:0.5 animations:^{
        [self.searchTableView mas_updateConstraints:^(MASConstraintMaker *make) {
          make.left.equalTo(self.view).offset(kScreenWidth);
        }];
      } completion:^(BOOL finished) {
        self.isSearching = NO;
        self.searchTableView.dataArray = @[];
        self.bottomView.dataSource = dataArray;
        [self.bottomView.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        NSDictionary *location = poiInfo[@"location"];
        CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake([location[@"latitude"] doubleValue], [location[@"longitude"] doubleValue]);
        
        //    //展示我的位置图标
        [self.mapView setCenterCoordinate:centerCoordinate animated:YES];
        MAPointAnnotation *annotation =  [MAPointAnnotation new];
        annotation.coordinate = centerCoordinate;
        [self.mapView removeAnnotations:self.mapView.annotations];
        [self.mapView addAnnotation:annotation];
      }];
    });
    
  };
  
  
  self.searchbar.addressChooseBackBlock = ^(NSDictionary * _Nonnull resultDic) {
    @strongify(self);
    NSDictionary *dataDic = nil;
    
    
    if (![resultDic[@"province"] isKindOfClass:[NSString class]]) {
      dataDic = resultDic[@"province"];
    }
    if (![resultDic[@"city"] isKindOfClass:[NSString class]]) {
      dataDic = resultDic[@"city"];
    }
    if (![resultDic[@"area"] isKindOfClass:[NSString class]]) {
      dataDic = resultDic[@"area"];
    }
    if (![resultDic[@"street"] isKindOfClass:[NSString class]]) {
      dataDic = resultDic[@"street"];
    }
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([dataDic[@"latitude"] gj_hasValue] ? [dataDic[@"latitude"] floatValue] : 0, [dataDic[@"longitude"] gj_hasValue] ? [dataDic[@"longitude"] floatValue]:0);
    self.searchTableView.dataArray = @[];
    [self queryLocationGeoWith:coordinate];
  };
  
  self.bottomView.didSelectedBlcok = ^(NSDictionary * _Nonnull info) {
    @strongify(self);
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([info[@"latitude"] doubleValue], [info[@"longitude"] doubleValue]);
    
    //    //展示我的位置图标
    [self.mapView setCenterCoordinate:coordinate animated:YES];
    MAPointAnnotation *annotation =  [MAPointAnnotation new];
    annotation.coordinate = coordinate;
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView addAnnotation:annotation];
  };
  
  self.bottomView.buttonClickBlock = ^(NSDictionary * _Nonnull info) {
    @strongify(self);
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:info];
//    NSDictionary *location = dic[@"location"];
    [dic setValue:dic[@"latitude"] forKey:@"lat"];
    [dic setValue:dic[@"longitude"] forKey:@"lon"];
//    [dic setValue:dic[@"address"] forKey:@"street"];
    [dic setValue:dic[@"district"] forKey:@"area"];
    [GJUtil sendNotificationForRNEventEmitterWithActionKey:@"map_position" parameter:dic];
    [self dismissViewControllerAnimated:YES completion:nil];
  };
}

- (void)queryLocationGeoWith:(CLLocationCoordinate2D)coordinate{
  //展示我的位置图标
  [self.mapView setCenterCoordinate:coordinate animated:YES];
  MAPointAnnotation *annotation =  [MAPointAnnotation new];
  annotation.coordinate = coordinate;
  [self.mapView removeAnnotations:self.mapView.annotations];
  [self.mapView addAnnotation:annotation];
  @weakify(self);
  [[GJLocationUtil shareInstance] searchPOIWithCoordinate:coordinate city:([self.addressDic[@"city"] gj_hasValue] ?  self.addressDic[@"city"] : @"") complete:^(NSArray * _Nonnull resultArray) {
    @strongify(self);
    if (resultArray.count > 0) {
      NSDictionary *dic = resultArray.firstObject;
      NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
      [dictionary setObject:dic[@"city"] forKey:@"city"];
      [dictionary setObject:dic[@"district"] forKey:@"area"];
      self.searchbar.dataDictionary = [dictionary mutableCopy];
      self.bottomView.dataSource = resultArray;
    }
  }];
}

#pragma mark -- buttonClick
- (void)navBackButtonClickAction:(UIButton *)sender{
  if (self.isSearching) {
    [self.view endEditing:YES];
    self.isSearching = NO;
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
      @strongify(self);
      [UIView animateWithDuration:0.5 animations:^{
        [self.searchTableView mas_updateConstraints:^(MASConstraintMaker *make) {
          make.left.equalTo(self.view).offset(kScreenWidth);
        }];
      } completion:^(BOOL finished) {
        self.searchbar.address = @"";
        self.searchTableView.dataArray = @[];
      }];
    });
  }else{
    [self dismissViewControllerAnimated:YES completion:nil];
  }
}
- (void)buttonClickAction:(UIButton *)sender{
  //locationBtn
  [self updateLocation];
}

/// 更新定位位置
- (void)updateLocation{
  MBProgressHUD *hud = [MBProgressHUD cr_showLoadinWithView:self.view text:@""];
  @weakify(self);
  __block NSInteger cycleTime = 5;
  
  [[GJLocationUtil shareInstance] getLocationWithCommplete:^(CLLocationCoordinate2D coordinate, NSDictionary * _Nonnull addressDic, NSError * _Nonnull error) {
    @strongify(self);
    if (error != nil) {
      cycleTime --;
      if (cycleTime<=0) {
        [hud cr_hide];
        [MBProgressHUD cr_showToastWithView:self.view text:@"获取位置信息失败"];
        [[GJLocationUtil shareInstance] stopSerialLocation];
      }
      return;
    }
    [hud cr_hide];
    //停止更新位置信息
    [[GJLocationUtil shareInstance] stopSerialLocation];
    
    //展示我的位置图标
    [self queryLocationGeoWith:coordinate];
  }];
  
}

#pragma mark -- BMKMapViewDelegate
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate{
  [self queryLocationGeoWith:coordinate];
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
  if ([annotation isKindOfClass:[MAPointAnnotation class]])
  {
    static NSString *reuseIndetifier = @"annotationReuseIndetifier";
    MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    if (annotationView == nil)
    {
      annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                    reuseIdentifier:reuseIndetifier];
    }
    
    annotationView.image = [UIImage imageNamed:@"map_selectedAnn.png"];
    return annotationView;
  }
  return nil;
}
#pragma mark -- getter


-(GJMapSearchBarView *)searchbar{
  if (!_searchbar) {
    _searchbar = [[GJMapSearchBarView alloc]init];
  }
  return _searchbar;
}

- (MAMapView *)mapView{
  if (!_mapView) {
    _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    //设置mapView的代理
    _mapView.delegate = self;
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = MAUserTrackingModeNone;
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    _mapView.zoomLevel = 16;
    for (UIView *view in _mapView.subviews) {
      if ([view isKindOfClass:[UIImageView class]]) {
        [view removeFromSuperview];
      }
    }
  }
  return _mapView;
}

- (UIButton *)backButton{
  if (!_backButton) {
    _backButton = [UIButton new];
    [_backButton setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(navBackButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _backButton;
}
- (UIButton *)locationButton{
  if (!_locationButton) {
    _locationButton = [UIButton new];
    [_locationButton setImage:[UIImage imageNamed:@"mapModule_location"] forState:UIControlStateNormal];
    [_locationButton addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _locationButton;
}

- (GJLocationUtil *)util{
  if (!_util) {
    _util = [GJLocationUtil new];
  }
  return _util;;
}
- (GJMapSelectedPointBottmView *)bottomView{
  if (!_bottomView) {
    _bottomView = [GJMapSelectedPointBottmView new];
  }
  return _bottomView;
}
- (GJSearchTableView *)searchTableView{
  if (!_searchTableView) {
    _searchTableView = [GJSearchTableView new];
  }
  return _searchTableView;
}

- (UIView *)navigatinoView{
  if (!_navigatinoView) {
    _navigatinoView = [[UIView alloc]initWithFrame:CGRectZero];
    _navigatinoView.backgroundColor = [UIColor whiteColor];
  }
  return _navigatinoView;
}
@end
